// page/location/location.js

import {
  apiBaseUrl,
  tencentMapApiKey,
  maxCommitLocationTimeout,
} from '../../config';
import {getNowFormatDate} from '../../utils/common'
// const db = wx.cloud.database();
// const yjlight_comment = db.collection('yjlight_comment');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    debug: false,
    isShowMask: false,
    logList: [],
    showingLocationList: [],
    locationList: [],
    wxopenid: '',
    tmpLocationDict: {

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const autoCommit = options.autoCommit;
    const wxopenid = wx.getStorageSync('wxopenid');
    this.setData({
      wxopenid,
    });
    if(autoCommit=='1'){
      this.commitLoction();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  log(...args){
    // logMsg = logMsg.toString();
    
    if(!this.data.debug){
      console.log.apply(this,args);
    }else{
    const logList = this.data.logList;
    args.forEach(arg=>{
      if(typeof(arg)=='object'){
        arg = JSON.stringify(arg);
      }
      logList.unshift(arg);
      console.log(arg);
    });
    this.setData({
      logList: [...logList],
    });
    }

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this;
    const apiUrl = `${apiBaseUrl}/list_location_by_wxopenid?page=1&wxopenid=ox-6X5F0urrzu-mruGM-AWauQ0OI`;
    wx.request({
      url: apiUrl,
      success(res) {
        if (res.data.code === 0) {
          const locationList = res.data.data;
          that.renderHander(locationList);
        } else {
          var logMsg = `73-73 request apiUrl: ${apiUrl} , data is not expert... res: `;
          that.log(logMsg, res);
        }
      },
      fail(err) {
        that.log(`request apiUrl: ${apiUrl} failed... err:`, err);
      }
    })
  },

  renderHander(locationList){
    const coreLocationDictList = locationList.splice(0,15).map(locationDict=>{
      this.log(`53-53 method:::::renderHander locationDict: `, locationDict);
      const address_component = JSON.parse(locationDict.addr_component_json);
      address_component['create_time'] = locationDict['create_time'];
      return address_component;
    });
    this.setData({
      locationList,
      coreLocationDictList,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  commitLoction() {
    this.setData({
      isShowMask: true,
    });
    setTimeout(()=>{
      if(this.data.isShowMask===true){
        this.setData({
          isShowMask: false,
        });
      }
    }, maxCommitLocationTimeout)
    this.getUserLocation();
  },

  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        vm.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        } else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  getLocation: function () {
    const that = this
    wx.getLocation({
      type: 'wgs84',
      altitude: true,
      isHighAccuracy: true,
      highAccuracyExpireTime: 2000,
      success: function (res) {
        that.log(res)
        const tmpLocationDict = {
          latitude: res.latitude,
          longitude: res.longitude
        };
        that.setData({tmpLocationDict: {...tmpLocationDict}})
        // 构建请求地址
        // 逆解析接口 /ws/geocoder/v1
        var qqMapApi = 'http://apis.map.qq.com/ws/geocoder/v1/' + "?location=" + tmpLocationDict.latitude + ',' +
        tmpLocationDict.longitude + "&key=" + tencentMapApiKey + "&get_poi=1";
        that.sendRequest(qqMapApi);
      },
      fail: function () {
        wx.showToast({
          title: '获取位置信息失败',
          icon: 'none'
        })
      }
    })
  },

  sendRequest:function(qqMapApi) {
    const that = this
    wx.request({
      url: qqMapApi,
      header: {
        'Content-Type': 'application/json'
      },
      data: {},
      method:'GET',
      success: (res) => {
        console.log(res)
        if (res.statusCode == 200 && res.data.status == 0) {
          // 从返回值中提取需要的业务地理信息数据 国家、省、市、县区、街道
          that.log(`198-198 method:::::sendRequest:::res.data.result:`, res.data.result);
          const tmpLocationDict = that.data.tmpLocationDict;
          // "addr_seg_json": null, 
          // "addr_str": "\u961c\u9633", 
          // "pois_json": null, 
          // "wxopenid": "ox-6X5F0urrzu-mruGM-AWauQ0OI"
          const result = res.data.result;
          tmpLocationDict['addr_str'] = result.address;
          tmpLocationDict['addr_info_json'] = JSON.stringify(result.ad_info);
          tmpLocationDict['addr_component_json'] = JSON.stringify(result.ad_info);
          tmpLocationDict['addr_pois_json'] = JSON.stringify(result.pois);
          tmpLocationDict['wxopenid'] = that.data.wxopenid;
          that.log(`210-210 method:::::sendRequest:::tmpLocationDict:`, tmpLocationDict);
          that.setData({tmpLocationDict: {...tmpLocationDict}});
          const saveToDatabaseApi = `${apiBaseUrl}/insert_location_by_wxopenid`;
          wx.request({
            method: 'POST',
            url: saveToDatabaseApi,
            data: tmpLocationDict,
            fail(err){
              that.log(`216-216 method:::::sendRequest:::fail:: saveToDatabaseApi:${saveToDatabaseApi} , err:`, err);
            },
            success(res){
              that.log(`216-216 method:::::sendRequest:::success:: saveToDatabaseApi:${saveToDatabaseApi} , res:`, res);
              const locationList = that.data.locationList;
              tmpLocationDict['create_time'] = getNowFormatDate(new Date());
              locationList.unshift(tmpLocationDict);
              // that.setData({locationList: {...locationList}});
              that.renderHander(locationList);
              that.setData({
                isShowMask: false,
              });
            }
          })

          // that.setData({ nation: res.data.result.address_component.nation });
          // that.setData({ province: res.data.result.address_component.province });
          // that.setData({ city: res.data.result.address_component.city });
          // that.setData({ district: res.data.result.address_component.district });
          // that.setData({ street: res.data.result.address_component.street });
        }else{
          that.log(`226-226 method:::::sendRequest:::fail:: request qqMapApi: ${qqMapApi}, incorrect res... res.statusCode:${res.statusCode} && res.data.status: ${res.data.status}`)
        }
      }
    })
  },

})